<template>
  <a-card :bordered="false">
    <a-spin :spinning="loading">
      <a-form :form="form" @submit="handleSubmit">
        <a-card title="自动采购配置" :bordered="false">
          <a-form-item label="是否启用自动采购" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-switch v-decorator="['autoPurchaseEnabled', { valuePropName: 'checked' }]" />
          </a-form-item>
          
          <a-form-item label="自动采购执行周期" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-select
              v-decorator="['autoPurchaseCron', { rules: [{ required: true, message: '请选择执行周期' }] }]"
              placeholder="请选择执行周期"
            >
              <a-select-option value="0 0 2 * * ?">每天凌晨2点</a-select-option>
              <a-select-option value="0 0 2 ? * MON">每周一凌晨2点</a-select-option>
              <a-select-option value="0 0 2 1 * ?">每月1日凌晨2点</a-select-option>
            </a-select>
          </a-form-item>
          
          <a-form-item label="是否需要审批" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-switch v-decorator="['approvalRequired', { valuePropName: 'checked' }]" />
          </a-form-item>
        </a-card>
        
        <a-card title="通知设置" :bordered="false" style="margin-top: 24px">
          <a-form-item label="是否启用通知" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-switch v-decorator="['notifyEnabled', { valuePropName: 'checked' }]" />
          </a-form-item>
          
          <a-form-item label="通知邮箱" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-textarea
              v-decorator="['notifyEmails', { rules: [{ validator: validateEmails }] }]"
              placeholder="多个邮箱请用逗号分隔"
              :rows="4"
            />
          </a-form-item>
        </a-card>
        
        <div style="text-align: center; margin-top: 24px;">
          <a-button type="primary" html-type="submit" :loading="submitLoading" v-if="hasPermission('wms:purchase:config:edit')">保存配置</a-button>
          <a-button type="primary" style="margin-left: 10px" @click="handleGenerateAutoPurchase" :loading="generateLoading" v-if="hasPermission('wms:purchase:auto:generate')">手动触发自动采购</a-button>
        </div>
      </a-form>
    </a-spin>
  </a-card>
</template>

<script>
import { getAction, postAction, putAction } from '@/api/manage'
import { USER_AUTH, SYS_BUTTON_AUTH } from '@/store/mutation-types'

export default {
  name: 'PurchaseConfig',
  data() {
    return {
      form: this.$form.createForm(this),
      loading: false,
      submitLoading: false,
      generateLoading: false,
      labelCol: { span: 4 },
      wrapperCol: { span: 16 },
      model: {},
      url: {
        getConfig: '/wms/purchase/auto/config',
        updateConfig: '/wms/purchase/auto/config',
        generatePurchase: '/wms/purchase/auto/generate'
      },
      permissionList: []
    }
  },
  created() {
    // 加载配置
    this.loadConfig();
    
    // 加载权限数据
    this.loadPermissionData();
  },
  methods: {
    // 加载权限数据
    loadPermissionData() {
      // 从sessionStorage获取权限
      let authList = JSON.parse(sessionStorage.getItem(USER_AUTH) || "[]")
      
      // 如果sessionStorage中没有权限，尝试从localStorage获取
      if (!authList || authList.length === 0) {
        authList = JSON.parse(localStorage.getItem(USER_AUTH) || "[]")
      }
      
      // 从按钮权限中获取
      const buttonAuth = JSON.parse(sessionStorage.getItem(SYS_BUTTON_AUTH) || localStorage.getItem(SYS_BUTTON_AUTH) || "[]")
      
      // 合并权限
      if (buttonAuth && buttonAuth.length > 0) {
        authList = authList.concat(buttonAuth)
      }
      
      // 提取action字段
      this.permissionList = authList.map(auth => auth.action || auth)
    },
    
    // 判断是否有权限
    hasPermission(permission) {
      if (!permission) return true // 如果未指定权限，默认有权限
      
      // 检查权限列表中是否包含指定权限
      if (this.permissionList.includes(permission)) {
        return true
      }
      
      // 检查权限列表中是否包含以逗号分隔的多个权限
      for (let perm of this.permissionList) {
        if (perm && perm.includes(',')) {
          const perms = perm.split(',')
          if (perms.includes(permission)) {
            return true
          }
        }
      }
      
      return false
    },
    
    loadConfig() {
      this.loading = true;
      getAction(this.url.getConfig).then(res => {
        if (res.success) {
          this.model = res.result || {};
          
          this.$nextTick(() => {
            this.form.setFieldsValue({
              autoPurchaseEnabled: this.model.autoPurchaseEnabled === 1,
              autoPurchaseCron: this.model.autoPurchaseCron || '0 0 2 * * ?',
              approvalRequired: this.model.approvalRequired === 1,
              notifyEnabled: this.model.notifyEnabled === 1,
              notifyEmails: this.model.notifyEmails || ''
            });
          });
        } else {
          this.$message.error(res.message || '加载配置失败');
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    validateEmails(rule, value, callback) {
      if (!value || !this.form.getFieldValue('notifyEnabled')) {
        callback();
        return;
      }
      
      const emails = value.split(',');
      const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      
      for (let i = 0; i < emails.length; i++) {
        const email = emails[i].trim();
        if (email && !emailRegex.test(email)) {
          callback(`第 ${i + 1} 个邮箱格式不正确`);
          return;
        }
      }
      
      callback();
    },
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          this.submitLoading = true;
          
          const formData = {
            id: this.model.id,
            autoPurchaseEnabled: values.autoPurchaseEnabled ? 1 : 0,
            autoPurchaseCron: values.autoPurchaseCron,
            approvalRequired: values.approvalRequired ? 1 : 0,
            notifyEnabled: values.notifyEnabled ? 1 : 0,
            notifyEmails: values.notifyEmails
          };
          
          putAction(this.url.updateConfig, formData).then(res => {
            if (res.success) {
              this.$message.success('保存成功');
              this.loadConfig();
            } else {
              this.$message.error(res.message || '保存失败');
            }
            this.submitLoading = false;
          }).catch(() => {
            this.submitLoading = false;
          });
        }
      });
    },
    handleGenerateAutoPurchase() {
      this.$confirm({
        title: '确认生成采购单',
        content: '系统将根据当前物料预警状态自动生成采购单，确定继续吗？',
        onOk: () => {
          this.generateLoading = true;
          postAction(this.url.generatePurchase).then(res => {
            if (res.success) {
              this.$message.success('自动生成采购单成功');
              // 可以跳转到采购单列表页面
              this.$router.push('/wms/purchase/list');
            } else {
              this.$message.error(res.message || '自动生成采购单失败');
            }
            this.generateLoading = false;
          }).catch(() => {
            this.generateLoading = false;
          });
        }
      });
    }
  }
}
</script>

<style scoped>
</style> 